import {Source, SourceState} from "./Source";
import {LatLngBounds} from "../geom/LatLngBounds";
import {FeatureCollection} from "@turf/helpers";
import Axios from "axios";
import {Layer} from "../layer/Layer";
import {FreeMap} from "../";

export class GeoJsonSource extends Source {
    public data: URL;

    protected cacheData: FeatureCollection;

    constructor(sourceId: string, data: URL) {
        super(sourceId);
        this.data = data;
    }

    public addTo(map: FreeMap): void {
        super.addTo(map);
        this.requestData();
    }

    requestData(): void {
        if (this.cacheData) {
            return
        }
        this.createHTTPRequest();
    }

    connectLayer(layer: Layer) {
        super.connectLayer(layer);

        if (this.state == SourceState.LOADED) {
            layer.onSourceDataChange(this.cacheData);
        }
    }

    protected createHTTPRequest() {
        this.state = SourceState.READY;

        Axios.get(this.data.toString())
            .then(value => {
                if (value.status == 200) {
                    this.cacheData = value.data;
                    this.state = SourceState.LOADED;
                    this.pushDataToLayer(this.cacheData);
                } else {
                    this.state = SourceState.ERROR;
                    console.error("get source %s data error:%s", this.sourceId, value.statusText);
                }
            })
            .catch(reason => {
                this.state = SourceState.ERROR;
                console.error("get source %s data error:%o", this.sourceId, reason);
            });
    }
}
